
#----------------------------------------------------------------------------------------------
# Helper

listArgToName<-function(ls,arg) {
	names(ls)[which(ls==arg)]
}

markMax <- function(xs,maxChar=3,normalChar=1) { chars=rep(normalChar,length(xs));chars[which.max(xs)]=maxChar ; chars }

# extract elements of list from [[1]]-> [1]
unpack<-function(ls) {
 	r<-numeric(as.integer(length(ls)))
 	for(i in 1:length(ls)) r[i]=ls[[i]]
 	r
}

# e.g. map(dbs_stats,"avg.silwidth")
map     <- function(cs, methodname) sapply(cs, function(c) c[[methodname]])

zeros<-function(n) matrix(rep(0,n*n),n,n)
# 
renumber<-function(ns) {
	ret <- as.numeric(length(ns)) 
	newcol = 1
	for(i in 1:length(ns)) { 
		if( ns[i] > 0 ) {
			ret[which(ns==ns[i])]=newcol;
			ns[ns==ns[i]]=0
			newcol = newcol + 1;
		}	
		 
	} 
	ret
}

removeindices <- function(datass,idxs) { 
	for(d in names(datass)) 
		for(a in names(datass[[d]])) 
			for(i in names(datass[[d]][[a]]$indices)) 
				if(i %in% idxs){ datass[[d]][[a]]$indices[[i]]=NULL }
	return(datass) 
}

showMaxIndices<- function(adss,idxName) {
for(d in names(adss)) 
		for(a in names(adss[[d]])) if(! a %in% c("datasetName","dataset"))  
			 print(paste(d,a,round(max(adss[[d]][[a]]$indices[[idxName]]),2),sep=","))
}			 

# TODO factor out in extra file to reduce dep. from RGL
require(rgl)
# show partition in 3d
showPoints3d<-function(d,rp) {
	rgl.clear()
	partition=renumber(rp)
	rgl.points(d,col=rainbow(max(partition))[partition],size=4)
	rgl.bbox()
}

showSpheres3d<-function(d,rp,radius=6,parts=NULL,alpha=0.4) {

	rgl.clear()
	partition =renumber(rp)
	
	if(is.null(parts)) parts=1:max(partition)
	
	idxs=which(partition %in% parts)
	cols=rainbow(max(partition[idxs]))[partition[idxs]]
	#cols=heat.colors(max(partition[idxs]))[partition[idxs]]
	#cols=terrain.colors(max(partition[idxs]))[partition[idxs]]
	rgl.spheres(x=d[idxs,],radius=radius,color=cols,alpha=alpha,smooth=T)
	rgl.bbox( color = c("#333377","white")
			, emission="#333377"
			, specular="#3333FF"
			, shininess=5, alpha=0.8 
			)

}

showSpheres3dSample<-function(sample,radius=6) {
	showSpheres3d(sample$d,sample$rp,radius)
}

